/**
 * 以 w+ 模式打开文本文档, 并测试读写
 */
#include <stdio.h>
#include "../Utils/FileIOUtils.h"

static const char *WRITE_PATH = "../Read_Write_Test/5.w+模式测试写&读.txt";

void w_plus_test();

int main() {
    //1. w+ 测试
    w_plus_test();

    return EXIT_SUCCESS;
}

//1. w+ 测试
void w_plus_test() {
    FILE *file = file_open_w_plus(WRITE_PATH);  //文件会被清空 or 创建

    //写字符串
    int fail0 = file_puts("1.asdfsf涉及到福建省sd d额\n", file);
    int fail1 = file_puts("2.jdgd使劲地发撒抵抗力方式历史地理撒地方啊 d\n", file);

    //将光标移回去 -10位
    int fail2 = file_seek(file, -10, SEEK_CUR);
    printf("1.光标从SEEK_CUR(当前位置)偏移 %d 位\n", -10);
    long pos0 = file_tell(file);
    printf("光标当前位置: pos0 = %ld\n", pos0);   //64

    //读1
    int c;
    printf("第1次读取:");
    while ((c = file_getc(file)) != -1) {   //"地方啊 d\r\n"
        printf("%c", c);
    }

    //再偏移回去
    int fail3 = file_seek(file, -30, SEEK_CUR);
    long pos1 = file_tell(file);
    printf("光标偏移 %d, 当前位置: pos1 = %ld\n", -30, pos1);   //44

    //再写
    int fail4 = file_puts("3.插入第3句.\n", file);
//    int fail4 = file_puts("3.这是插入的第3句话 d额fsjf撒地方数到法师发收到\n", file);
    if (fail4) {
        printf("第3次写失败: fail4 = %d\n", fail4);
    } else {
        printf("第3次写成功!\n");
    }
    long pos2 = file_tell(file);
    printf("光标当前位置: pos2 = %ld\n", pos2);   //58

    //写入后, 调用fseek()随便传个值, 否则继续读会死循环
    file_seek(file, 0, SEEK_CUR);

    //读2
    int SIZE = sizeof(char) * 1000;
//    char arr[1000] = {0};      //读取成功
    char *arr = malloc(SIZE);    //读取成功
    printf("第2次读取, ");
    while (!file_eof(file)) {   //死循环
//        memset(arr, 0, SIZE);
        char *str = file_gets(arr, SIZE, file);
        if (str) {
            printf("arr = %s", arr);    //"地理撒地方啊 d\r\n"
        }
    }
    free(arr);

    file_close(file);
}
